package validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import command.GraduateForm;
import command.UserForm;

@Component
public class GraduateFormValidator implements Validator {
	@Autowired
	private UserFormValidator userFormValidator;
	@Autowired
	public GraduateFormValidator(UserFormValidator userFormValidator) {
		if (userFormValidator == null) {
	          throw new IllegalArgumentException("The supplied [userFormValidator] is required and must not be null.");
	      }
	      if (!userFormValidator.supports(UserForm.class)) {
	          throw new IllegalArgumentException(
	            "The supplied [UserFormValidator] must support the validation of [User] instances.");
	      }
		
		this.userFormValidator = userFormValidator;
	}
	
	@Override
	public boolean supports(Class<?> clazz) {
		return GraduateForm.class.isAssignableFrom(clazz);
	}
	
	@Override
	public void validate(Object target, Errors errors) {
		
		GraduateForm form = (GraduateForm) target;
		if(form.getStudentCode()==null || form.getStudentCode().isEmpty()) {
			errors.rejectValue("studentCode", "empty");
		}
		
		if(form.getBirthdate() == null) {
			errors.rejectValue("birthdate", "empty");
		}
		
		// El graduate form solo se usa para crear un profile inicial.
		// Asi que solo valida los campos obligatorios del profile
		
		ValidationUtils.invokeValidator(this.userFormValidator, (UserForm)target, errors);
	}
}
